// 认证相关功能

// 检查用户是否已登录
function checkAuth() {
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = 'login.html';
        return false;
    }

    // 验证令牌
    fetch('/api/auth/me', {
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => {
        if (!response.ok) throw new Error('令牌无效');
        return response.json();
    })
    .then(data => {
        if (data.success && data.data) {
            document.getElementById('username').textContent = data.data.username;
            return true;
        } else {
            throw new Error('获取用户信息失败');
        }
    })
    .catch(error => {
        console.error('认证失败:', error);
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = 'login.html';
        return false;
    });

    return true;
}

// 退出登录
function logout() {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    window.location.href = 'login.html';
}

// 登录函数
function login(username, password) {
    return fetch('/api/auth/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            localStorage.setItem('token', data.token);
            localStorage.setItem('user', JSON.stringify(data.user));
            return { success: true };
        } else {
            return { success: false, message: data.message };
        }
    })
    .catch(error => {
        console.error('登录失败:', error);
        return { success: false, message: '登录请求失败，请重试' };
    });
}

// 注册函数
function register(username, password) {
    return fetch('/api/auth/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            return { success: true };
        } else {
            return { success: false, message: data.message };
        }
    })
    .catch(error => {
        console.error('注册失败:', error);
        return { success: false, message: '注册请求失败，请重试' };
    });
}

// 页面加载时执行认证检查
document.addEventListener('DOMContentLoaded', function() {
    // 如果当前页面是登录或注册页面，则不进行认证检查
    if (window.location.pathname.includes('login.html') || window.location.pathname.includes('register.html')) {
        return;
    }
    
    checkAuth();
    
    // 绑定退出登录按钮事件
    const logoutBtn = document.getElementById('logoutBtn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', function(e) {
            e.preventDefault();
            logout();
        });
    }
});